// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
// import './util/flexible'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import 'babel-polyfill'
import { getCookie } from './util/common'
import { loadOffices } from './util/common'
import * as echarts from 'echarts'
import moment from 'moment'
import store from './store'
import axios from './api/api'
Vue.prototype.$echarts = echarts
Vue.prototype.$moment = moment
Vue.config.productionTip = false
Vue.use(Vuex);

Vue.use(ElementUI);

window.bus = new Vue();
window.store = store;
/* eslint-disable no-new */

//自定义指令
Vue.directive('has', {
  inserted: function (el, binding) {
    if (!Vue.prototype.$_has(binding.value)) {
      el.parentNode.removeChild(el);
    }
  }
});



//全局方法
Vue.prototype.$_has = function (value) {
  let isExist = false
  var permissions = getCookie("permissions");
  if (permissions === undefined || permissions == null) {
    return false;
  }
  if (permissions.indexOf(value) > -1) {
    isExist = true;
  }
  return isExist;
}
// 获取当下时间格式yyyy-MM-dd
Vue.prototype.getNowFormatDate = function () {
  var date = new Date();
  var seperatorl = '-';
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentDate = year + seperatorl + month + seperatorl + strDate;
  return currentDate;
}

Vue.prototype.global = global;



//根据用户角色权限动态生成路由表


router.beforeEach((to, from, next) => {
  //判断该路由是否需要登录权限
  console.log(1)
  if (to.meta.requireAuth) {
    console.log("2")
    if (sessionStorage.getItem('isLogin')) {
      console.log("3")
      if (store.getters.roles.length === 0) {
        store.commit("setLoginUser");
        store.commit("setRoles");
        loadOffices(this);
        let user = store.getters.loginUser;
        let office = user.data.office;
        let roles = store.getters.roles;
        // let offices = store.getters.offices;
        console.log("roles", roles);
        // console.log("offices", offices)
        let userInfo = {
          roles,
          office,
        }
        console.log(userInfo),
          store.dispatch("generateRoutes", userInfo).then((value) => {
            console.log("vuex-routes", store.getters.routes)
            console.log(value);
            router.addRoutes(value);
            next({ ...to, replace: true })
          })
      } else {
        next();
      }
    } else {
      next({
        path: '/',
      })
    }
  } else {
    next()
  }
})


let vue = new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})